
#include <stdio.h>
#include <string.h>
#include "sc_internal.h"
#include "sc_error.h"
char *strtok_hier(char *str, char **saveptr)
{
    //printf("%s\n",*saveptr);
    char* c;
    if(str != NULL){
        *saveptr = str;
    }
    if(*saveptr == NULL){
        return NULL;
    }
    /*查找到 "/" ,则返回位置，否则返回NULL*/
    c = strchr(*saveptr,'/');
    if(c){
        str = *saveptr;
        *saveptr=c+1;
        c[0]='\0';
    }
    else if(*saveptr){
        str = *saveptr;
        *saveptr = NULL;
    }
    return str;
}
/*
fun: 将url 切割成独立的数组
subtopic: 订阅url a/b/c
local_sub: 临时变量
topics: 输出的topic 数组
sharename: 暂时无用
*/
int sub_topic_tokenise(const char *subtopic, char **local_sub, char ***topics, const char **sharename)
{
    char *saveptr = NULL;
    char* token;
    int count = 0;
    int topic_index = 0;
    int i;
    size_t len;
    
    len = strlen(subtopic);
    if(len == 0)
    {
        return SC_ERR_INVAL;
    }
    *local_sub = strdup(subtopic);
    if((*local_sub) == NULL) 
        return SC_ERR_NOMEM; 

    //计算sub里面有多少个topic 
    saveptr = *local_sub;
    while(saveptr)
    {
        saveptr = strchr(&saveptr[1],'/');
        count++;
    }
    *topics = calloc((size_t)(count+3),sizeof(char *));
    if(topics == NULL)
    {
        free(*local_sub);
        return SC_ERR_NOMEM;
    }
    //如果第一个topic 不是$ 开头，则将第一个topic 变成“”
    if((*local_sub)[0] != '$')
    {
        (*topics)[topic_index] = "";
        topic_index++;
    }

    //获取topic 并存放进topicsl里面
    token = strtok_hier(*local_sub, &saveptr);
    while(token)
    {
        (*topics)[topic_index] = token;
        topic_index ++;
        token = strtok_hier(NULL, &saveptr);
    }
    return SC_OK;
}